package top.zywork.controller;

import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.validation.BindingResult;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import top.zywork.annotation.AppAuthFilter;
import top.zywork.annotation.SysLog;
import top.zywork.common.*;
import top.zywork.constant.FileConstants;
import top.zywork.dto.GoodsCategoryDTO;
import top.zywork.dto.PagerDTO;
import top.zywork.enums.DatePatternEnum;
import top.zywork.enums.ResponseStatusEnum;
import top.zywork.enums.UploadTypeEnum;
import top.zywork.query.GoodsCategoryQuery;
import top.zywork.service.GoodsCategoryService;
import top.zywork.service.UploadService;
import top.zywork.vo.GoodsCategoryVO;
import top.zywork.vo.PagerVO;
import top.zywork.vo.ResponseStatusVO;

import java.util.List;

/**
 * GoodsCategoryController控制器类<br/>
 *
 * 创建于2019-07-04<br/>
 *
 * @author http://zywork.top 王振宇
 * @version 1.0
 */
@RestController
@RequestMapping("/goods-category")
@AppAuthFilter(ignoreUrls = {
        "/goods-category/admin/upload/**"
})
@Slf4j
public class GoodsCategoryController extends BaseController {

    @Value("${storage.provider}")
    private String storageProvider;

    @Value("${storage.local.compressSizes}")
    private String compressSizes;

    @Value("${storage.local.compressScales}")
    private String compressScales;

    @Value("${storage.local.goodsCategory.imgParentDir}")
    private String imgParentDir;

    @Value("${storage.local.goodsCategory.imgDir}")
    private String imgDir;

    @Value("${storage.local.goodsCategory.imgUrl}")
    private String imgUrl;

    @Value("${storage.local.goodsCategory.keepFileName}")
    private Boolean keepFileName;

    @Value("${storage.deleteBaseDir}")
    private String deleteBaseDir;

    private GoodsCategoryService goodsCategoryService;

    private UploadService uploadService;

    @PostMapping("admin/save")
    @SysLog(description = "后台保存GoodsCategoryVO")
    public ResponseStatusVO save(@RequestBody @Validated GoodsCategoryVO goodsCategoryVO, BindingResult bindingResult) {
        if (bindingResult.hasErrors()) {
            return ResponseStatusVO.dataError(BindingResultUtils.errorString(bindingResult), null);
        }
        goodsCategoryService.save(BeanUtils.copy(goodsCategoryVO, GoodsCategoryDTO.class));
        return ResponseStatusVO.ok("添加成功", null);
    }

    @PostMapping("admin/batch-save")
    @SysLog(description = "后台批量保存GoodsCategoryVO")
    public ResponseStatusVO saveBatch(@RequestBody @Validated List<GoodsCategoryVO> goodsCategoryVOList, BindingResult bindingResult) {
        if (bindingResult.hasErrors()) {
            return ResponseStatusVO.dataError(BindingResultUtils.errorString(bindingResult), null);
        }
        goodsCategoryService.saveBatch(BeanUtils.copyListObj(goodsCategoryVOList, GoodsCategoryDTO.class));
        return ResponseStatusVO.ok("批量添加成功", null);
    }

    @GetMapping("admin/remove/{id}")
    @SysLog(description = "后台删除GoodsCategoryVO")
    public ResponseStatusVO removeById(@PathVariable("id") Long id) {
        Object obj = goodsCategoryService.getById(id);
        if (null == obj) {
            return ResponseStatusVO.error("数据不存在", null);
        }
        GoodsCategoryVO goodsCategoryVO = BeanUtils.copy(obj, GoodsCategoryVO.class);
        if (org.apache.commons.lang.StringUtils.isNotEmpty(goodsCategoryVO.getPicUrl())) {
            uploadService.deleteImg(deleteBaseDir, goodsCategoryVO.getPicUrl());
        }
        goodsCategoryService.removeById(id);
        return ResponseStatusVO.ok("删除成功", null);
    }

    @PostMapping("admin/batch-remove")
    @SysLog(description = "后台批量删除GoodsCategoryVO")
    public ResponseStatusVO removeByIds(@RequestBody String[] ids) {
        goodsCategoryService.removeByIds(StringUtils.strArrayToLongArray(ids));
        return ResponseStatusVO.ok("批量删除成功", null);
    }

    @PostMapping("admin/update")
    @SysLog(description = "后台更新GoodsCategoryVO")
    public ResponseStatusVO update(@RequestBody @Validated GoodsCategoryVO goodsCategoryVO, BindingResult bindingResult) {
        if (bindingResult.hasErrors()) {
            return ResponseStatusVO.dataError(BindingResultUtils.errorString(bindingResult), null);
        }
        return updateObject(goodsCategoryVO);
    }

    @PostMapping("admin/update-status")
    @SysLog(description = "后台更新商品类目状态")
    public ResponseStatusVO updateStatus(@RequestBody GoodsCategoryVO goodsCategoryVO) {
        return updateObject(goodsCategoryVO);
    }

    /**
     * 更新对象信息
     * @param goodsCategoryVO
     * @return
     */
    private ResponseStatusVO updateObject(GoodsCategoryVO goodsCategoryVO) {
        int updateRows = goodsCategoryService.update(BeanUtils.copy(goodsCategoryVO, GoodsCategoryDTO.class));
        if (updateRows == 1) {
            return ResponseStatusVO.ok("更新成功", null);
        } else {
            return ResponseStatusVO.dataError("数据版本号有问题，在此更新前数据已被更新", null);
        }
    }

    @PostMapping("admin/batch-update")
    @SysLog(description = "后台批量更新GoodsCategoryVO")
    public ResponseStatusVO updateBatch(@RequestBody @Validated List<GoodsCategoryVO> goodsCategoryVOList, BindingResult bindingResult) {
        if (bindingResult.hasErrors()) {
            return ResponseStatusVO.dataError(BindingResultUtils.errorString(bindingResult), null);
        }
        goodsCategoryService.updateBatch(BeanUtils.copyListObj(goodsCategoryVOList, GoodsCategoryDTO.class));
        return ResponseStatusVO.ok("批量更新成功", null);
    }

    @PostMapping("admin/active")
    @SysLog(description = "后台激活或冻结GoodsCategoryVO")
    public ResponseStatusVO active(@RequestBody GoodsCategoryVO goodsCategoryVO) {
        goodsCategoryService.update(BeanUtils.copy(goodsCategoryVO, GoodsCategoryDTO.class));
        return ResponseStatusVO.ok("激活或冻结成功", null);
    }

    @PostMapping("admin/batch-active")
    @SysLog(description = "后台批量激活或冻结GoodsCategoryVO")
    public ResponseStatusVO activeBatch(@RequestBody @Validated List<GoodsCategoryVO> goodsCategoryVOList) {
        goodsCategoryService.updateBatch(BeanUtils.copyListObj(goodsCategoryVOList, GoodsCategoryDTO.class));
        return ResponseStatusVO.ok("批量激活或冻结成功", null);
    }

    @GetMapping("admin/one/{id}")
    public ResponseStatusVO getById(@PathVariable("id") Long id) {
        GoodsCategoryVO goodsCategoryVO = new GoodsCategoryVO();
        Object obj = goodsCategoryService.getById(id);
        if (obj != null) {
            goodsCategoryVO = BeanUtils.copy(obj, GoodsCategoryVO.class);
        }
        return ResponseStatusVO.ok("查询成功", goodsCategoryVO);
    }

    @GetMapping("admin/all")
    public ResponseStatusVO listAll() {
        PagerDTO pagerDTO = goodsCategoryService.listAll();
        PagerVO pagerVO = BeanUtils.copy(pagerDTO, PagerVO.class);
        pagerVO.setRows(BeanUtils.copyList(pagerDTO.getRows(), GoodsCategoryVO.class));
        return ResponseStatusVO.ok("查询成功", pagerVO);
    }

    @PostMapping("admin/all-cond")
    public ResponseStatusVO listAllByCondition(@RequestBody GoodsCategoryQuery goodsCategoryQuery) {
        PagerDTO pagerDTO = goodsCategoryService.listAllByCondition(goodsCategoryQuery);
        PagerVO pagerVO = BeanUtils.copy(pagerDTO, PagerVO.class);
        pagerVO.setRows(BeanUtils.copyList(pagerDTO.getRows(), GoodsCategoryVO.class));
        return ResponseStatusVO.ok("查询成功", pagerVO);
    }

    @PostMapping("any/all-cond")
    public ResponseStatusVO anyListAllByCondition(@RequestBody GoodsCategoryQuery goodsCategoryQuery) {
       return listAllByCondition(goodsCategoryQuery);
    }

    @PostMapping("admin/pager-cond")
    public ResponseStatusVO listPageByCondition(@RequestBody GoodsCategoryQuery goodsCategoryQuery) {
        PagerDTO pagerDTO = goodsCategoryService.listPageByCondition(goodsCategoryQuery);
        PagerVO pagerVO = BeanUtils.copy(pagerDTO, PagerVO.class);
        pagerVO.setRows(BeanUtils.copyList(pagerDTO.getRows(), GoodsCategoryVO.class));
        return ResponseStatusVO.ok("查询成功", pagerVO);
    }

    /**
     * 条件查询商品类目
     * @param goodsCategoryQuery
     * @return
     */
    @PostMapping("any/pager-cond")
    public ResponseStatusVO anyListPageByCondition(@RequestBody GoodsCategoryQuery goodsCategoryQuery) {
        return listPageByCondition(goodsCategoryQuery);
    }

    /**
     * 通过第一级商品类目获取二级和三级商品类目
     * @param goodsCategoryQuery
     * @return
     */
    @PostMapping("any/by-first-level-category")
    public ResponseStatusVO anyListCategoryByFirstLevelCategoryId(@RequestBody GoodsCategoryQuery goodsCategoryQuery) {
        PagerDTO pagerDTO = goodsCategoryService.listCategoryByFirstLevelCategory(goodsCategoryQuery);
        PagerVO pagerVO = BeanUtils.copy(pagerDTO, PagerVO.class);
        pagerVO.setRows(BeanUtils.copyList(pagerDTO.getRows(), GoodsCategoryVO.class));
        return ResponseStatusVO.ok("查询成功", pagerVO);
    }

    /**
     * 上传类目封面图片
     * @param categoryId 类目编号
     * @param file 图片文件
     * @return
     */
    @PostMapping("admin/upload/{categoryId}")
    @SysLog(description = "后台上传类目封面图片", requestParams = false)
    public ResponseStatusVO upload(@PathVariable("categoryId") Long categoryId, MultipartFile file) {
        String date = DateFormatUtils.format(DateUtils.currentDate(), DatePatternEnum.DATE.getValue());
        UploadUtils.UploadOptions uploadOptions = UploadUtils.UploadOptions.builder().uploadParentDir(imgParentDir).uploadDir(imgDir + FileConstants.SEPARATOR + date)
                .dbSaveUrl(imgUrl + FileConstants.SEPARATOR + date).keepFileName(keepFileName).build();
        uploadOptions.generateCompressSizes(compressSizes);
        ResponseStatusVO responseStatusVO = uploadService.uploadFile(storageProvider, file, UploadTypeEnum.IMAGE.getAllowedExts(), UploadTypeEnum.IMAGE.getMaxSize(), uploadOptions);
        if (responseStatusVO.getCode().intValue() == ResponseStatusEnum.OK.getCode().intValue()) {
            GoodsCategoryDTO goodsCategoryDTO = GoodsCategoryDTO.builder().id(categoryId).picUrl(responseStatusVO.getData().toString()).build();
            goodsCategoryService.update(goodsCategoryDTO);
        }
        return responseStatusVO;
    }

    /**
     * 获取三级类目信息，并取到顶级的类目
     * @param categoryId
     * @return
     */
    @GetMapping("any/level3-info/{categoryId}")
    public ResponseStatusVO anyGetOneCategory(@PathVariable("categoryId") Long categoryId) {
        return goodsCategoryService.getLevel3InfoByCategory(categoryId);
    }

    @Autowired
    public void setGoodsCategoryService(GoodsCategoryService goodsCategoryService) {
        this.goodsCategoryService = goodsCategoryService;
    }

    @Autowired
    public void setUploadService(UploadService uploadService) {
        this.uploadService = uploadService;
    }
}
